const { db, query } = require("../../db/db");
const util = require("util");
const dayjs = require("dayjs");
const moment = require("moment");

async function SignInByUserId(req, res) {
  let UserId = Number(req.params.username);
  const Date = req.body.Date;
  db.getConnection((err, connection) => {
    connection.beginTransaction(async (err) => {
      if (err) {
        throw err;
      }
      const insert_sign_in = util.format(
        "Insert INTO User_Sign_In_Day \
      (UserId,SignInDate,CreateTime) \
      Values(%s,'%s','%s')",
        UserId,
        Date,
        moment().format("YYYY-MM-DD HH:mm:ss")
      );
      connection.query(insert_sign_in, (err, result) => {
        if (err) {
          throw err;
        }
        //2.累计天数
        const previousDay = dayjs(Date).subtract(1, "day").format("YYYY-MM-DD");

        const select_yestoday_isSign = util.format(
          "Select SignInDayId from User_Sign_In_Day Where UserId=%s and SignInDate='%s'",
          UserId,
          previousDay
        );

        connection.query(select_yestoday_isSign, (err, result) => {
          if (err) {
            throw err;
          }
          if (result.length > 0) {
            const update_yestoday_signInDay = util.format(
              "Update User Set KeepSignDay=KeepSignDay+1 Where UserId=%s",
              UserId
            );
            connection.query(update_yestoday_signInDay, (err, result) => {
              if (err) {
                throw err;
              }
            });
          } else {
            const update_yestoday_signInDay = util.format(
              "Update User Set KeepSignDay=1 Where UserId=%s",
              UserId
            );
            connection.query(update_yestoday_signInDay, (err, result) => {
              if (err) {
                throw err;
              }
            });
          }
          //3.累计
          const update_Addday_signInDay = util.format(
            "Update User Set AddSignDay=AddSignDay+1 Where UserId=%s",
            UserId
          );
          connection.query(update_Addday_signInDay, (err, result) => {
            if (err) {
              throw err;
            }
          });

          //4.矿石
          const update_OreNum_signInDay = util.format(
            "Update User Set OreNum=OreNum+100 Where UserId=%s",
            UserId
          );
          connection.query(update_OreNum_signInDay, (err, result) => {
            if (err) {
              throw err;
            }

            connection.commit(function (err) {
              if (err) {
                connection.rollback(function () {
                  throw err;
                });
              }
              res.send({
                status: 0,
              });
              console.log("Transaction completed successfully.");
            });
          });
        });
      });
    });
  });
}

module.exports = { SignInByUserId };

/* const mysql = require('mysql2/promise');  
const moment = require('moment');  
const util = require('util');  
  
// 假设你已经有了数据库连接配置  
const pool = mysql.createPool({  
  host: 'localhost',  
  user: 'your_username',  
  database: 'your_database',  
  password: 'your_password',  
  waitForConnections: true,  
  connectionLimit: 10,  
  queueLimit: 0  
});  
  
async function SignInByUserId(req, res) {  
  try {  
    const connection = await pool.getConnection();  
    await connection.beginTransaction();  
  
    const UserId = Number(req.params.username);  
    const Date = req.body.Date;  
  
    const createTime = moment().format("YYYY-MM-DD HH:mm:ss");  
    const insert_sign_in = `INSERT INTO User_Sign_In_Day (UserId, SignInDate, CreateTime) VALUES (?, ?, ?)`;  
    await connection.query(insert_sign_in, [UserId, Date, createTime]);  
  
    // 2. 累计天数  
    const previousDay = moment(Date).subtract(1, 'days').format('YYYY-MM-DD');  
    const select_yestoday_isSign = `SELECT SignInDayId FROM User_Sign_In_Day WHERE UserId = ? AND SignInDate = ?`;  
    const [rows] = await connection.query(select_yestoday_isSign, [UserId, previousDay]);  
  
    if (rows.length > 0) {  
      const update_yestoday_signInDay = `UPDATE User SET KeepSignDay = KeepSignDay + 1 WHERE UserId = ?`;  
      await connection.query(update_yestoday_signInDay, [UserId]);  
    } else {  
      await connection.query(`UPDATE User SET KeepSignDay = 1 WHERE UserId = ?`, [UserId]);  
    }  
  
    // 3. 累计  
    const update_Addday_signInDay = `UPDATE User SET AddSignDay = AddSignDay + 1 WHERE UserId = ?`;  
    await connection.query(update_Addday_signInDay, [UserId]);  
  
    // 4. 矿石  
    const update_OreNum_signInDay = `UPDATE User SET OreNum = OreNum + 100 WHERE UserId = ?`;  
    await connection.query(update_OreNum_signInDay, [UserId]);  
  
    await connection.commit();  
    res.send({ status: 0 });  
    console.log("Transaction completed successfully.");  
  } catch (err) {  
    await connection.rollback();  
    console.error("Transaction failed:", err);  
    res.status(500).send({ status: 1, message: "Internal Server Error" });  
  } finally {  
    connection.release();  
  }  
} */
